package com.chenxbook.modules.jbpm4.assign;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.jbpm.api.cmd.Command;
import org.jbpm.api.cmd.Environment;
import org.jbpm.api.task.Task;
import org.jbpm.pvm.internal.task.TaskImpl;

import java.util.Date;
import java.util.List;

/**
 * Description
 * <br>  客户化任务查询命令
 *
 * @author chenxbook
 * @date 2021-08-08
 **/
public class CustomTaskQueryCommand implements Command<List<Task>> {
    private static final long serialVersionUID = 8241396023595108801L;
    /**
     * 任务优先级
     */
    private int taskPriority;
    /**
     * 任务描述
     */
    private String taskDescLike;
    /**
     * 任务创建时间范围-起始时间
     */
    private Date taskCreateFrom;
    /**
     * 任务创建时间范围-结束时间
     */
    private Date taskCreateTo;


    public CustomTaskQueryCommand(int taskPriority, String taskDescLike, Date taskCreateFrom, Date taskCreateTo) {
        this.taskPriority = taskPriority;
        this.taskDescLike = taskDescLike;
        this.taskCreateFrom = taskCreateFrom;
        this.taskCreateTo = taskCreateTo;
    }

    public CustomTaskQueryCommand() {
    }

    @Override
    public List<Task> execute(Environment environment) {
        //从Environment对象中可以获取包括Hibernate会话在内的所有工作流引擎运行时资源
        Session session = environment.get(Session.class);
        //使用Hibernate3的条件查询
        Criteria criteria = session.createCriteria(TaskImpl.class);
        //任务的字段属性在Hibernate配置文件jbpm.task.hbm.xml中可以看到
        //设置任务优先级参数到对应字段priority
        if (taskPriority != 0) {
            criteria.add(Restrictions.eq("priority", taskPriority));
        }
        //设置任务描述参数到对应字段description，支持模糊查询
        if (StringUtils.isNotBlank(taskDescLike)) {
            criteria.add(Restrictions.like("description", "%" + taskDescLike + "%"));
        }
        //设置任务的创建时间范围，即设定createTime所在的区间范围
        if (taskCreateFrom != null && taskCreateTo != null) {
            criteria.add(Restrictions.between("createTime",taskCreateFrom,taskCreateTo));
        }
        //执行查询
        List<?> list = criteria.list();
        //返回任务列表
        return (List<Task>) list;
    }
}
